package view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.laoxinwen.app.R;

/**
 * Created by ilioili on 2015/3/16.
 */
public class FixedImageView extends ImageView {
    private int h = 1;
    private int w = 1;

    public FixedImageView(Context context) {
        this(context, null);
    }

    public FixedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.FixedImageView);
        w = array.getInt(R.styleable.FixedImageView_w, 1); //提供默认值，放置未指定
        h = array.getInt(R.styleable.FixedImageView_h, 1);
        array.recycle();
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        //自动计算matrix，横向居中，竖向顶部
        Drawable drawable = getDrawable();
        if (getScaleType() == ScaleType.MATRIX && drawable != null) {
            Matrix matrix = new Matrix();
            float scale;
            float dx = 0, dy = 0;

            int dwidth = drawable.getIntrinsicWidth();
            int dheight = drawable.getIntrinsicHeight();

            int vwidth = r - l;
            int vheight = b - t;

            if (dwidth * vheight > vwidth * dheight) {
                scale = (float) vheight / (float) dheight;
                dx = (vwidth - dwidth * scale) * 0.5f;
            } else {
                scale = (float) vwidth / (float) dwidth;
                //dy = (vheight - dheight * scale) * 0.5f;
            }

            matrix.setScale(scale, scale);
            matrix.postTranslate(dx, 0);
            //matrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));

            setImageMatrix(matrix);
        }
        return super.setFrame(l, t, r, b);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth() * h / w);
    }
}
